/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
/*
 * CalibrateFrame.java
 *
 * Created on 18-ene-2012, 17:40:17
 */
package Vista.Calibrar;

import Vista.configuracion.MenuPal;
import java.awt.AWTException;
import java.awt.Point;
import java.awt.Robot;
import java.awt.Toolkit;
import java.awt.event.InputEvent;
import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.edisoncor.gui.util.WindowsUtil;
import wiiusej.WiiUseApiManager;
import wiiusej.Wiimote;
import wiiusej.values.IRSource;
import wiiusej.wiiusejevents.physicalevents.ExpansionEvent;
import wiiusej.wiiusejevents.physicalevents.IREvent;
import wiiusej.wiiusejevents.physicalevents.MotionSensingEvent;
import wiiusej.wiiusejevents.physicalevents.WiimoteButtonsEvent;
import wiiusej.wiiusejevents.utils.WiimoteListener;
import wiiusej.wiiusejevents.wiiuseapievents.*;

/**
 *
 * @author Jhon Jairo
 */
public class CalibrateFrame extends javax.swing.JFrame implements WiimoteListener {

    public Robot robot;
    private Wiimote wiimote;
    private int x1 = 0;
    private int y1 = 0;
    static Calibrar c;
    static CalibrateFrame calibrateFrame;
    public static int mousey;
    public static int mousex;
    public static float bateryLevel;
    static boolean move;
    static int count;
    int rango=10;
    Point pm;

    /**
     * Creates new form CalibrateFrame
     */
    public CalibrateFrame(Wiimote wim) {
        setUndecorated(true);
        WindowsUtil.makeWindowsOpacity(this, 0.6f);
        initComponents();
        wiimote = wim;
        wiimote.addWiiMoteEventListeners(this);
        setSize((int) Toolkit.getDefaultToolkit().getScreenSize().getWidth(), (int) Toolkit.getDefaultToolkit().getScreenSize().getHeight());
        jLabel1.setVisible(false);
        jLabel2.setVisible(false);
        jLabel3.setVisible(false);
        jLabel4.setVisible(false);
        c = new Calibrar(jLabel1, jLabel2, jLabel3, jLabel4);
        c.start();
        pm = new Point(0, 0);
        try {
            robot = new Robot();
        } catch (AWTException e) {
            e.printStackTrace();
        }
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        panelNice1 = new org.edisoncor.gui.panel.PanelNice();
        jLabel1 = new javax.swing.JLabel();
        exit = new javax.swing.JLabel();
        jLabelInfo = new javax.swing.JLabel();
        jLabel3 = new javax.swing.JLabel();
        jLabel4 = new javax.swing.JLabel();
        jLabel2 = new javax.swing.JLabel();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

        jLabel1.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Vista/Images/miraT.png"))); // NOI18N
        jLabel1.setText("jLabel1");

        exit.setForeground(new java.awt.Color(240, 240, 240));
        exit.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Vista/Images/exit.png"))); // NOI18N
        exit.setText("Salir");
        exit.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                exitMouseClicked(evt);
            }
        });

        jLabelInfo.setForeground(new java.awt.Color(255, 255, 255));
        jLabelInfo.setText("No recibo señal");

        jLabel3.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Vista/Images/miraT.png"))); // NOI18N

        jLabel4.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Vista/Images/miraT.png"))); // NOI18N

        jLabel2.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Vista/Images/miraT.png"))); // NOI18N

        javax.swing.GroupLayout panelNice1Layout = new javax.swing.GroupLayout(panelNice1);
        panelNice1.setLayout(panelNice1Layout);
        panelNice1Layout.setHorizontalGroup(
            panelNice1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(panelNice1Layout.createSequentialGroup()
                .addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 52, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addComponent(jLabel2))
            .addGroup(panelNice1Layout.createSequentialGroup()
                .addGap(123, 123, 123)
                .addGroup(panelNice1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jLabelInfo, javax.swing.GroupLayout.PREFERRED_SIZE, 282, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(exit, javax.swing.GroupLayout.PREFERRED_SIZE, 151, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(0, 69, Short.MAX_VALUE))
            .addGroup(panelNice1Layout.createSequentialGroup()
                .addComponent(jLabel3)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addComponent(jLabel4))
        );
        panelNice1Layout.setVerticalGroup(
            panelNice1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(panelNice1Layout.createSequentialGroup()
                .addGroup(panelNice1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jLabel1)
                    .addComponent(jLabel2))
                .addGroup(panelNice1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(panelNice1Layout.createSequentialGroup()
                        .addGap(18, 18, 18)
                        .addComponent(exit)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(jLabelInfo, javax.swing.GroupLayout.PREFERRED_SIZE, 34, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(0, 75, Short.MAX_VALUE)
                        .addComponent(jLabel3))
                    .addGroup(panelNice1Layout.createSequentialGroup()
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                        .addComponent(jLabel4))))
        );

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(panelNice1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(panelNice1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void exitMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_exitMouseClicked
        System.exit(0);
    }//GEN-LAST:event_exitMouseClicked

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) throws IOException, ClassNotFoundException {
        System.setProperty("java.net.preferIPv4Stack", "true");

        Wiimote[] wiimotes = WiiUseApiManager.getWiimotes(1, false, WiiUseApiManager.WIIUSE_STACK_MS);
        if (wiimotes.length > 0) {
            System.out.println(wiimotes[0]);
            wiimotes[0].activateIRTRacking();
            count = 0;
            calibrateFrame = new CalibrateFrame(wiimotes[0]);
            calibrateFrame.setVisible(true);

        } else {
//            String path = System.getProperty("java.library.path");
//            System.out.println(path);
            System.out.println("No wiimotes found !!!");
            NoWimmote now = new NoWimmote();
            now.setResizable(false);
            now.setVisible(true);
        }
    }

    @Override
    public void onStatusEvent(StatusEvent e) {
        bateryLevel = e.getBatteryLevel();
    }

    @Override
    public void onIrEvent(IREvent e) {
        IRSource[] list = e.getIRPoints();
        if (list.length > 0) {
            move = true;
            count = 0;
            //Get infrared cordinates
            x1 = (int) list[0].getX();
            y1 = (int) list[0].getY();
            if (c.isCalibrar()) {
                c.setPoint(new Point(x1, y1));
            }
            int width = (int) Toolkit.getDefaultToolkit().getScreenSize().getWidth();
            int heigth = (int) Toolkit.getDefaultToolkit().getScreenSize().getHeight();
            mousex = (int) Math.round(((double) x1 / c.getAnchoX()) * width);
            mousey = (int) Math.round(((double) y1 / c.getAltoY()) * heigth);
            //System.out.println("pmx= "+pm.getX()+"total="+(c.getResolucionX() - mousex));
            //mouse presionado
            new mouseControlClick().start();
            //movimiento mouse
            new MouseMoveClass().start();
            if ((pm.getX() > (c.getResolucionX() - mousex)+rango )||(pm.getY()> (c.getResolucionY() - mousey )+rango)||(pm.getX() < (c.getResolucionX() - mousex)-rango)
                    ||(pm.getY() < (c.getResolucionY() - mousey)-rango )){
            //mouse liberado
            new Mouserelease().start();
            }
        } 
    }

    public class mouseControlClick extends Thread {
        public void run() {
            robot.mousePress(16);
        }
    }

    public class MouseMoveClass extends Thread {

        public void run() {
            pm.setLocation(c.getResolucionX() - mousex, c.getResolucionY() - mousey);
            robot.mouseMove(c.getResolucionX() - mousex, c.getResolucionY() - mousey);
        }
    }

    public class Mouserelease extends Thread {
        public void run() {
            robot.mouseRelease(InputEvent.BUTTON1_DOWN_MASK);
              try {
                Thread.sleep(30);
            } catch (InterruptedException ex) {
                Logger.getLogger(Calibrar.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
    }

    @Override
    public void onButtonsEvent(WiimoteButtonsEvent wbe) {
    }

    @Override
    public void onMotionSensingEvent(MotionSensingEvent mse) {
    }

    @Override
    public void onExpansionEvent(ExpansionEvent ee) {
    }

    @Override
    public void onDisconnectionEvent(DisconnectionEvent de) {
    }

    @Override
    public void onNunchukInsertedEvent(NunchukInsertedEvent nie) {
    }

    @Override
    public void onNunchukRemovedEvent(NunchukRemovedEvent nre) {
    }

    @Override
    public void onGuitarHeroInsertedEvent(GuitarHeroInsertedEvent ghie) {
    }

    @Override
    public void onGuitarHeroRemovedEvent(GuitarHeroRemovedEvent ghre) {
    }

    @Override
    public void onClassicControllerInsertedEvent(ClassicControllerInsertedEvent ccie) {
    }

    @Override
    public void onClassicControllerRemovedEvent(ClassicControllerRemovedEvent ccre) {
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JLabel exit;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    public static javax.swing.JLabel jLabelInfo;
    private org.edisoncor.gui.panel.PanelNice panelNice1;
    // End of variables declaration//GEN-END:variables
}
